<?php
namespace app\common\service;

use GuzzleHttp\Client;
use think\Config;
use think\Log;

class OrangeMoneyService
{
    protected $config;
    protected $client;
    protected $mode;
    
    public function __construct()
    {
        $this->config = Config::get('orange');
        $this->mode = $this->config['mode'];
        $this->client = new Client();
    }
    
    /**
     * 发起支付请求
     * @param float $amount 金额（最小单位，如XOF的分）
     * @param string $orderId 订单号
     * @param string $customerPhone 客户手机号（带国家码，如+225XXXXXXXXX）
     * @return array
     */
    public function initiatePayment($amount, $orderId, $customerPhone)
    {
        try {
            $url = $this->config['api_endpoints'][$this->mode]['initiate'];
            
            $data = [
                'merchant_key' => $this->config['api_key'],
                'merchant_id' => $this->config['merchant_id'],
                'terminal_id' => $this->config['terminal_id'],
                'amount' => $amount,
                'currency' => $this->config['currency'],
                'order_id' => $orderId,
                'customer_msisdn' => $customerPhone,
                'return_url' => $this->config['return_url'],
                'notif_url' => $this->config['notify_url'],
                'country' => $this->config['country'],
                'service' => 'orange_money'
            ];
            
            $response = $this->client->post($url, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->getAccessToken()
                ],
                'json' => $data
            ]);
            
            $result = json_decode($response->getBody()->getContents(), true);
            
            // 记录日志
            Log::record('Orange Money initiate: ' . json_encode($result), 'pay');
            
            return [
                'success' => true,
                'data' => $result
            ];
        } catch (\Exception $e) {
            Log::record('Orange Money error: ' . $e->getMessage(), 'pay');
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 查询支付状态
     * @param string $transactionId 交易ID
     * @return array
     */
    public function checkPaymentStatus($transactionId)
    {
        try {
            $url = str_replace('{transactionId}', $transactionId, 
                $this->config['api_endpoints'][$this->mode]['status']);
            
            $response = $this->client->get($url, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $this->getAccessToken()
                ]
            ]);
            
            $result = json_decode($response->getBody()->getContents(), true);
            return [
                'success' => true,
                'data' => $result
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
    
    /**
     * 获取访问令牌
     * @return string
     */
    protected function getAccessToken()
    {
        // 实际实现中需要处理token缓存，避免重复请求
        $response = $this->client->post('https://api.orange.com/oauth/v3/token', [
            'headers' => [
                'Authorization' => 'Basic ' . base64_encode($this->config['api_key'] . ':'),
                'Content-Type' => 'application/x-www-form-urlencoded'
            ],
            'form_params' => [
                'grant_type' => 'client_credentials'
            ]
        ]);
        
        $result = json_decode($response->getBody()->getContents(), true);
        return $result['access_token'];
    }
}